package com.aiapphub.BaseCode.controller;

import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.BaseCode.entity.Menu;
import com.aiapphub.BaseCode.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限管理控制器
 */
@RestController
@RequestMapping("/admin/acl/permission")
public class PermissionController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取权限(菜单/功能)列表
     */
    @GetMapping
    public ResponseResult getPermissionList() {
        List<Menu> menuTree = menuService.getMenuTree();
        return ResponseResult.okResult(menuTree);
    }

    /**
     * 删除一个权限项
     */
    @DeleteMapping("/remove/{id}")
    public ResponseResult removePermission(@PathVariable Long id) {
        boolean result = menuService.removeMenu(id);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "删除失败");
    }

    /**
     * 保存一个权限项
     */
    @PostMapping("/save")
    public ResponseResult addPermission(@RequestBody Menu menu) {
        boolean result = menuService.saveMenu(menu);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "保存失败");
    }

    /**
     * 更新一个权限项
     */
    @PutMapping("/update")
    public ResponseResult updatePermission(@RequestBody Menu menu) {
        boolean result = menuService.updateMenu(menu);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "更新失败");
    }

    /**
     * 查看某个角色的权限列表
     */
    @GetMapping("/toAssign/{roleId}")
    public ResponseResult toAssign(@PathVariable Long roleId) {
        // 获取所有权限列表
        List<Menu> allPermissions = menuService.getMenuTree();
        
        // 获取角色已分配的权限ID列表
        List<Long> assignedMenuIds = menuService.getMenuIdsByRoleId(roleId);
        
        // 构造返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("allPerms", allPermissions);
        result.put("assignedPermIds", assignedMenuIds);
        
        return ResponseResult.okResult(result);
    }

    /**
     * 给某个角色授权
     */
    @PostMapping("/doAssign")
    public ResponseResult doAssign(@RequestParam Long roleId, @RequestParam String permissionId) {
        // 由于没有实现角色权限关联的具体逻辑，这里暂时返回成功
        // 实际应用中需要保存角色和权限的关联关系到role_menu表
        return ResponseResult.okResult();
    }
}